(function(){
	window.portal = Function("return "+sessionStorage.getItem("sys"))();
	var pt = $("head>title");
	if (!pt.length) $("head").append("<title>中国电信股份有限公司新疆云网分析中心门户</title>");
	else pt.text("中国电信股份有限公司新疆云网分析中心门户");
	
	if (!portal) {
		$.ajax({url:"/getPortal",type:"post",async:false,dataType:"json",success:function(d){
			sessionStorage.setItem("apps",d.apps);
			sessionStorage.setItem("menus",d.menus);
			sessionStorage.setItem("sys",d.sys);
			window.portal = Function("return "+sessionStorage.getItem("sys"))();
			if (!portal) window.location.href = "/";
		},error:function(){
			window.location.href = "/";
		}});
	}
	
	//系统公告
	$.post("/getNotice",{id:getRequestParameter("portal").split(".")[0]},function(data){
		var idx = 0;
		//系统公告
		for(var i=0;i<data.length;i++){
			var d= data[i];
			if(sessionStorage.getItem("notice_"+d.notice_id)!="false") pushNotice(d,idx++,i);
		}
	},"json");
	
	function pushNotice(d,n,i,f){
		$.messager.show({
			cls:"notic-cls",timeout:0,width:322,height:210,title:"<div class='omission' style='width:90%;color:#fff;'>系统公告：</div>",border:'thin',
			msg:"<div class='sysNoticeContent'><div style='color:#D0021B;font-weight:bold;'>"+d.notice_name+":</div><div>"+d.notice_content+"</div></div>",
			style:{position:"fixed",background:"#D0021B",borderColor:"#D0021B",left:"",right:323*n,top:"",bottom:-document.body.scrollTop-document.documentElement.scrollTop},
			onClose:function(){
				//关闭后不在显示
				if(f) sessionStorage.setItem("fromLogin",false);
				else sessionStorage.setItem("notice_"+d.notice_id,false);
			}
		});
	}
	
	function getRequestParameter(name){
		var r = window.location.search.substr(1).match(new RegExp("(^|&)"+name+"=([^&]*)(&|$)"));
		return r!=null?decodeURI(r[2]):null;
	}
	
	var reqParam = portal.getRequestParameter = function(name){
		var r = window.location.search.substr(1).match(new RegExp("(^|&)"+name+"=([^&]*)(&|$)"));
		return r!=null?decodeURI(r[2]):null;
	}
	portal.setAppLink = function(link,id,url){ //给定的a标签添加点击应用链接
		url = getLinkurl(url);
		if (!url.target) url.href = url.href + (url.href.indexOf("?")>0?"&":"?") + "portal=" + getAppPath(id,apps,"");
		link.attr(url);
	}
	function getAppPath(id,apps,path){
		if (!apps) return null;
		for (var i=0; i<apps.length; i++){
			if (apps[i].id.split(",")[0]==id) return apps[i].id+path+"."+i;
			else {
				var p = getAppPath(id,apps[i].children,path+"."+i);
				if (p) return p;
			}
		}
	}
	function getPath(list,idx){
		var item = list[idx.shift()], path = item.text;
		if (idx.length) path += " > "+getPath(item.children,idx);
		return path;
	}
	function getFirsturl(menu){
		if (menu.attributes && menu.attributes.url) return menu.attributes.url;
		if (menu.children) {
			for (var i=0; i<menu.children.length; i++) {
				var url = getFirsturl(menu.children[i]);
				if (url!=null) return url;
			}
		}
		return null;
	}
	function getLinkurl(url){
		return url.indexOf("f:")==0?{href:url.substr(2).replace("${userId}",portal.userId)
			.replace("${userName}",encodeURI(portal.userName)).replace("${userRegion}",portal.regionId)
			.replace("${userHx}",portal.hxNumber),target:"_blank"}:{href:url};
	}
	function setLink(link,url){
		if (url) link.attr(getLinkurl(url));
		else link.addClass("disable");
	}
	
	window.changePwd = function changePwd() {
		$("#pwdDlg").form("submit", {
			url: "/changePwd",
			onSubmit: function () {
				return $(this).form("validate");
			},
			success: function (d) {
				var data = JSON.parse(d);
				if (data.code==0) {
					$("#pwdDlg").dialog("close");
					$.messager.alert("提示","密码修改成功！","info");
				} else $.messager.alert("提示",data.message,"error");
			}
		})
	}
	$.extend($.fn.validatebox.defaults.rules,{
		pwd:{
			validator:function(val,param){
				return new RegExp("(?=.{8,})([a-zA-Z]+\\d+)*(\\d+[a-zA-Z]+)*([a-zA-Z]+[!@#$%^&*_]+)*([!@#$%^&*_]+[a-zA-Z]+)*(\\d+[!@#$%^&*_]+)*([!@#$%^&*_]+\\d+)*$").test(val);
			},message:"请输入8位以上字母、数字、特殊字符组合密码串"
		},
		rpwd:{
			validator:function(val,param){
				return val===$("#npwd").passwordbox("getValue");
			},message:"请正确重复输入新密码"
		}
	});
	
	var apps = Function("return "+sessionStorage.getItem("apps"))()||[],menus = Function("return "+sessionStorage.getItem("menus"))()||[],appsMap = {};
	//转换成对象
	for(var i=0;i<apps.length;i++)  appsMap[apps[i].id]=apps[i];
	
	var path = reqParam("portal").split("."), funcId = path.shift(), isApp = funcId.indexOf(",")>0, moduleIdx = path[0], menuList,moduleId;
	if (path.length) {
		if (isApp && path.length>3) { //app大于3层
			var list
			if(path.length>4)
				list = apps[path[0]].children[path[1]].children[path[2]].children[path[3]].children;
			else
				list = apps[path[0]].children[path[1]].children[path[2]].children;
			if (list.length>1) menuList = list; //多于一个应用
		} else if (!isApp && menus[path[0]].children) { //有子菜单
			var list = menus[path[0]].children;
			if (path.length==2 && list.length>1 || path.length==3 || path.length==4) menuList = list;
		}
		if(isApp) moduleId= apps[path[0]].id;
		path = getPath(isApp?apps:menus, path);
	}
	var isHome = /首页$/.test(path), page = $(document.body).children(":not(link,script,style)"), url = portal.url||"",
		head = $("<div class='portal-banner'>\
				<div class='portal-head'>\
					    <div class='portal-logo'>\
					      <img src='../images/fxzx.jpg'alt='描述图片的文字' style='width: 130px; height: 25px;'>\
					    </div>\
					    <div class='portal-center'>\
					       <div class='portal-searchbox'><input type='text' placeholder='请输入搜索关键字'/><span/>\
							</div>\
					    </div>\
						<div class='portal-right'>\
								 <img src='../images/bot.png'alt='描述图片的文字' style='width: 28px; height: 28px;'> \
								 <div class='portal-systool'>\
									<span class='portal-user' title='"+portal.userName+"'>"+portal.userName+"</span><i class='arrow-down'></i>\
									<ul class='sys-drop'>\
										<li class='sys-drop-text' onclick='$(\"#pwdDlg\").dialog(\"center\").dialog(\"open\").form(\"reset\")' ><div class='type-title-cn'>密码重置<div class='type-title-cn-border'/></div></li>\
										<li class='sys-drop-text sys-logout'><div class='type-title-cn'>退出登陆<div class='type-title-cn-border'/></div></li>\
									</ul>\
								 </div>\
						</div>\
				</div>    \
				<div class='portal-head2'>\
				   <ul class=\"portal-module-list\"></ul>\
			    </div>\
				<div class='portal-page'></div>\
				<form id=\"pwdDlg\" class=\"easyui-dialog\" style=\"padding:6px;display:none;\" data-options=\"title:'密码修改',width:350,closed:true,modal:true,draggable:false,buttons:[\
				{text:'确定',iconCls:'icon-ok',handler:changePwd},{text:'取消',iconCls:'icon-cancel',handler:function(){$('#pwdDlg').dialog('close')}}]\"><table cellpadding=\"6\" style='width:100%;'>\
				<tr><td align=\"right\" width='80'>原密码</td><td><input name=\"opwd\" class=\"easyui-passwordbox\" data-options=\"width:'100%',required:true,missingMessage:'请输入原密码',delay:1000\"></td></tr>\
				<tr><td align=\"right\">新密码</td><td><input id=\"npwd\" name=\"npwd\" class=\"easyui-passwordbox\" data-options=\"width:'100%',required:true,validType:'pwd',missingMessage:'请输入新密码',delay:1000\"></td></tr>\
				<tr><td align=\"right\">确认新密码</td><td><input name=\"rnpwd\" class=\"easyui-passwordbox\" data-options=\"width:'100%',required:true,validType:'rpwd',missingMessage:'请重复输入新密码',delay:1000\"></td></tr>\
				</table></form>").prependTo(document.body).eq(0);
	var fixedHeight=$(window).height()-head.height()-20, autoTitle = !(reqParam("autoTitle")=="false");
	$(".portal-searchbox").children("input").keydown(function(e){
		if (e.keyCode==13) $(this).next().click();
	}).next().click(function(e){
		var cond = $.trim($(this).prev().val());
		if (cond) window.location.href = "/appSearch?portal=0&autoTitle=false&cond="+encodeURIComponent(cond);
	});
	if (menuList) { //有菜单导航
		var layout = $("<div id='lay' data-options='fit:true'>\
			<div data-options='region:\"west\",title:\"目录导航\",iconCls:\"icon-c-tab\",split:true,width:250,minWidth:250,cls:\"portal-menu-list sidemenu\"'></div>\
			<div data-options='region:\"center\",title:\""+(autoTitle?path+"<a style=\\\"display:none\\\">收藏</a>":"")+"\",iconCls:\"icon-c-app\",headerCls:\"portal-app-nav\"'></div></div>")
			.appendTo($(".portal-page").height(fixedHeight)).layout();
		var cp = layout.layout("panel","center"),wp = layout.layout("panel","west");
		cp.panel("body").append(page);
		var $ul =$("<ul/>").appendTo(wp.panel("body"));
		$(function(){
			$(".portal-page").children().layout("resize");//初始化时resize否则可能错位
			var tree = $ul.tree({data:menuList,onBeforeSelect:function(node){
				var t = $(this), isLeaf = t.tree("isLeaf",node.target);
				if (!isLeaf) t.tree("toggle",node.target);
				return isLeaf;
			},onSelect:function(node){
				if (funcId!=node.id) {
					var url = node.attributes.url,real = getLinkurl(node.attributes.url);
					if(url.indexOf("f:")==0) window.open(real.href);//外链
					else window.location.href = real.href;//其他
				}
			}});
			tree.tree("select",tree.tree("find",funcId).target);
		}); 
	} else {
		if (isHome) $(".portal-page").addClass("portal-page-no-space").append(page);
		else {
			page = $(".portal-page").append((autoTitle?"<div class='portal-app-nav panel-header'><div class='panel-title panel-with-icon'>"+
					path+"<a class='portal-btn-favor' style='display:none'>收藏</a></div><div class='panel-icon icon-c-app'></div></div>":"")+
					"<div class='portal-app-section"+(autoTitle?"":" portal-app-section-border")+"'></div>").children(":last").append(page);
			if (!(document.body.getAttribute("height")=="auto"||reqParam("autoHeight")=="true")) page.height(fixedHeight-(page.prev().outerHeight(true)||0)-(autoTitle?1:2));
		}
	}

	// 保存系统管理菜单
	var systemManagementMenu = null;
	for (var i=0; i<menus.length; i++){ //一级菜单模块
		var topBarApp=appsMap[menus[i].id];
		var hasTopBar = topBarApp?true:false,menu = menus[i],appId = menu.id||"",appText = menu.text||"";

		var menu = menus[i];
		var appId = menu.id || "";
		var appText = menu.text || "";

		if (appText === "系统管理") {
			// 如果菜单名称为"系统管理"，保存菜单信息
			systemManagementMenu = menu;
			continue; // 跳过当前菜单
		}

		var $menuLi = $("<li "+((!isApp&&moduleIdx==i||moduleId&&moduleId==menus[i].id)?" class='portal-module-active'":"")+" menuId="+appId+"><a>"+appText+"</a>"+(hasTopBar?"<i class='arrow-down'></i>":"")+"</li>")
			.appendTo(".portal-module-list").children().eq(0).attr("href",getFirsturl(menu));
		//加载应用菜单
		if(!hasTopBar) continue;//无子菜单
		var $cmenuBox= $('<div class="common-topbar-dropdown" appId='+topBarApp.id+'>\
				<div class="ace-common-menu-dropdown">\
					<div class="block-left">\
						<a class="block-left-title" target="_self" href="javascript:void(0)"><span>'+topBarApp.text+'</span><i class="arrow-black"></i></a>\
						<ul></ul>\
					</div>\
					<div class="block-center">\
						<div class="second-menu-wrap">\
							<div class="search-input-elem-wrap">\
								<i class="search-img"></i><input class="search-input-elem " placeholder="快捷搜索" value="">\
							</div>\
							<div class="second-menu-inner-wrap second-menu-inner-wrap-four"></div>\
						</div>\
					</div>\
				</div></div>').insertBefore($(".portal-page"));
		var capp = topBarApp.children||[];

		for(var j=0;j<capp.length;j++){
			var capp1 = capp[j];
			//第一版菜单
			var $reporBox = $('<div class="second-menu second-menu-max-four '+(j==0?"report-box-active":"")+'"></div>').appendTo($cmenuBox.find(".block-center .second-menu-inner-wrap-four"));
			$('<li appId='+capp[j].id+'>\
					<a class="type-title '+(j==0?" title-active":"")+'" href="javascript:void(0);" style="cursor: default;"><div class="type-title-cn"> '+capp[j].text+'<div class="type-title-cn-border"></div></div></a>\
				</li>').appendTo($cmenuBox.find(".block-left ul"));
			if(!capp1.children) continue;
			for(var k=0;k<capp1.children.length;k++){
				var $reportApp= $('<div class="menuA-second-item-wrap"><div class="next-menu-item-2" title="'+capp1.children[k].text+'">'+capp1.children[k].text+'</div><div class="next-menu-item-3"></div></div>').appendTo($reporBox);
				var $menu3App = $reportApp.find(".next-menu-item-3");
				if (capp1.children[k].children) {
					for(var m=0;m<capp1.children[k].children.length;m++){
						var n = capp1.children[k].children[m],isHot = n.attributes.is_hot ? true: false,isNew = n.attributes.is_new ? true: false;
						var c3 = $('<a class="second-menu-item-title-3">'+capp1.children[k].children[m].text+'<span/></a>').appendTo($menu3App);
						if(isHot) $('<img src="/images/hot.gif">').prependTo(c3.find("span"));
						else if(isNew) $('<img src="/images/new.gif">').prependTo(c3.find("span"));
						setLink(c3,getFirsturl(n));
					}
				}else{
					var n = capp1.children[k],isHot = n.attributes.is_hot ? true: false,isNew = n.attributes.is_new ? true: false;
					var c3 = $('<a class="second-menu-item-title-3">'+n.text+'<span/></a>').appendTo($menu3App);
					if(isHot) $('<img src="/images/hot.gif">').prependTo(c3.find("span"));
					else if(isNew) $('<img src="/images/new.gif">').prependTo(c3.find("span"));
					setLink(c3,getFirsturl(n));
				}
			}
		}
	}
	// 将系统管理菜单放在最后
	if (systemManagementMenu) {
		var $menuLi = $("<li menuId=" + systemManagementMenu.id + "><a>" + systemManagementMenu.text + "</a></li>")
			.appendTo(".portal-module-list").children().eq(0).attr("href", getFirsturl(systemManagementMenu));
	}
	//右侧用户菜单项
	$(".portal-systool").on("click",function(){$(".sys-drop").toggleClass("dropdown-active");})
	//导航栏事件
	$(".portal-module-list li").hover(function(){
		$(".common-topbar-dropdown").removeClass("dropdown-active");
		$(".common-topbar-dropdown[appId='"+$(this).attr("menuId")+"']").addClass("dropdown-active");
	})
	$(".common-topbar-dropdown,.sys-drop").mouseleave(function(){$(this).removeClass("dropdown-active")})
	$(".block-left ul li").on("click",function(){
			var $topBar = $(".ace-common-menu-dropdown:visible"), $titleBar = $topBar.find(".block-left ul li a"), $reportBar = $topBar.find(".block-center .second-menu-max-four");
			var $active = $(this).find("a");
			if($active.hasClass("title-active")) return;
			$titleBar.removeClass("title-active");
			$active.addClass("title-active");
			$(".search-input-elem ").val("");
			$(".dropdown-active .second-menu-inner-wrap-four .report-box-active").find(".menuA-second-item-wrap,.next-menu-item-2,a").show();
			$reportBar.removeClass("report-box-active");
			$reportBar.eq($(this).index()).addClass("report-box-active");
	});
	//应用过滤
	$(".search-input-elem ").on("input",function(e){ 
		var text = $(e.target).val().trim(),$actRpt = $(".dropdown-active .second-menu-inner-wrap-four .report-box-active");
		$actRpt.find("a").each(function(){
			if(text==""||$(this).text().toUpperCase().indexOf(text.toUpperCase())>-1){ $actRpt.find(".menuA-second-item-wrap").show();$(this).show();}
			else $(this).hide();
		})
		$actRpt.find(".menuA-second-item-wrap").each(function(){
			var len =$(this).find(".next-menu-item-3 a").filter(function(){return !$(this).is(":hidden");}).length;
			if(!len) {$(this).hide();$(this).find(".next-menu-item-2").hide();}
			else {$(this).show();$(this).find(".next-menu-item-2").show();}
		})
	})
	//登出
	$(".sys-logout").click(function(){
		$.post("/log",{type:2},function(){$.post("/logout",function(d){if(d.code==0) window.location.href="/";});});
	});
	$.post("/log",{type:isApp?3:4,content:funcId});

	$.ajaxSetup({beforeSend:function(xhr){
		if (/common\/getGridExcel$/.test(this.url)){
			if (this.data.indexOf("waterMark=")<0) {
				var date=new Date();
				this.data+="&waterMark="+portal.userId+"%20%20"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
			}
			if (this.data.indexOf("userId=")<0) this.data+="&userId="+portal.userId;
		}
	}});
}());